<template>
  <div id="app">
    <div class="second-div">
      <span v-if="dialogFormVisible1">
        <!--小区条件查询-->
        <div class="custom-icon-text" style="margin-top: -15px">
        <div class="search-form" style="width: 100%">
          <div style="width: 60px;height: 60px;margin-left: 10px;margin-top: 0px">
            <el-button icon="el-icon-s-data" class="custom-button">总数<br><br>{{total}}</el-button>
          </div>
          <el-form :model="formInline" ref="queryForm" size="small" :inline="true" style="margin-top: 10px" label-width="68px">
            <div style=" border-bottom: 1px solid #333;margin-bottom: 10px">
              <div style="margin-left: 450px;margin-top: -60px">
                <el-form-item label="小区名称">
                  <el-input v-model="formInline.plotName" placeholder="小区名称"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" style="margin-left: -11px"  @click="onSubmit"></el-button>
                  <el-button icon="el-icon-refresh" size="mini"@click="advancedSearch" >高级检索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置条件</el-button>
                </el-form-item>
              </div>
            </div>
            <div v-if="isAdvancedSearch" style="width: 100%;margin-top: 5px">
              <el-form-item label="所属辖区">
                <el-cascader
                  v-model="areasIds"
                  clearable
                  :options="areasList"
                  :props="{ expandTrigger: 'click' ,value: 'id', label: 'name', children: 'childrenList'}"
                  @change="aressChange">
                </el-cascader>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>

        <!--添加小区按钮-->
        <el-button style="margin-bottom: 10px;" type="success" @click="plotInsert">新增小区</el-button>
        <br>
        <el-row :gutter="8">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(item, index) in plotList" :key="index">
            <el-card class="box-card" :body-style="{padding: '15px'}">
              <div style="width: 25%" @click="plotDetails(item.id)">
                <div style="width: 150px;height: 150px">
                  <span style="margin-top: -5px;margin-left: 2px"><image-preview :src="item.plotPic" :width="140" :height="140"/></span>
                </div>
                <div style="width: 220px;height: 150px;margin-left: 150px;margin-top: -150px">
                  <h4 style="margin-top: -1px">
                    {{ item.plotName }}
                    <el-button type="primary" size="mini" icon="el-icon-edit" style="margin-left: 10px" circle @click.stop="plotUpdate(item.id)"></el-button>
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle @click.stop="plotDelete(item.id)"></el-button>
                  </h4>
                  <p>{{ item.address }}</p>
                  <p>辖区:{{ item.areasName!= null ? item.areasName : '暂无' }}</p>
                  <p>楼栋数：<span style="color: chocolate">{{ item.buildingNum != null ? item.buildingNum : 0 }}</span>栋 | 户数：<span style="color: chocolate">{{ item.actualBuilding!= null ? item.actualBuilding : 0 }}</span>户</p>
                </div>
                <div style="width: 350px;height: 150px">
                  <div class="box" style="width: 110px; height: 70px">实有人口<br>{{item.actualPopulation!= null ? item.actualPopulation : 0}}</div>
                  <div class="box" style="width: 110px;height: 70px;margin-left: 110px;margin-top: -70px">实有房屋<br>{{item.actualBuilding!= null ? item.actualBuilding : 0}}</div>
                  <div class="box" style="width: 110px;height: 70px;margin-left: 220px;margin-top: -70px">实有单位<br>{{item.actualUnit!= null ? item.actualUnit : 0}}</div>
                  <div class="box" style="width: 110px;height: 70px">实有车辆<br>{{item.actualVehicle!= null ? item.actualVehicle : 0}}</div>
                  <div class="box" style="width: 110px;height: 70px;margin-left: 110px;margin-top: -70px">实有力量<br>{{item.actualStrength!= null ? item.actualStrength : 0}}</div>
                  <div class="box" style="width: 110px;height: 70px;margin-left: 220px;margin-top: -70px">实有设备<br>{{item.actualEquipment!= null ? item.actualEquipment : 0}}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </span>
      <span v-if="dialogFormVisible">
        <h1 style="margin-left: 45px">{{this.title}}</h1>
        <div style="width: 100%;height: 100%">
        <div style="width: 490px;height: 630px">
          <el-form :model="plotParam">
            <el-form-item label="小区名称" :label-width="formLabelWidth">
              <el-input v-model="plotParam.plotName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="小区图片" :label-width="formLabelWidth">
              <image-upload v-model="plotParam.plotPic"/>
            </el-form-item>

            <el-form-item label="所属辖区" :label-width="formLabelWidth" v-if="title === '新增小区'">
              <el-cascader
                v-model="areasIds"
                :options="areasList"
                :props="{ expandTrigger: 'click' ,value: 'id', label: 'name', children: 'childrenList'}"

                @change="aressChange"></el-cascader>
              <!--              <el-input v-model="plotParam.areasId" autocomplete="off"></el-input>-->
            </el-form-item>
            <el-form-item label="所属辖区" :label-width="formLabelWidth" v-if="title === '修改小区'">
              <el-cascader
                v-model="plotParam.areasId"
                :options="areasList"
                :props="{ expandTrigger: 'click' ,value: 'id', label: 'name', children: 'childrenList'}"
                @change="aressChange"></el-cascader>

              <!--              <el-input v-model="plotParam.areasId" autocomplete="off"></el-input>-->
            </el-form-item>
            <h3 align="center" >请先选择所属辖区，获取辖区编号，再输入小区编号</h3>
            <el-form-item label="小区编号" :label-width="formLabelWidth">
              <el-input v-model="plotParam.code" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="所属地址" :label-width="formLabelWidth">
              <el-input v-model="plotParam.address" autocomplete="off"></el-input>
            </el-form-item>
            <!--            <el-form-item label="小区轮廓" :label-width="formLabelWidth">-->
            <!--              <el-input v-model="plotParam.outLine" autocomplete="off"></el-input>-->
            <!--            </el-form-item>-->
            <el-form-item label="小区中心点" :label-width="formLabelWidth" v-if="plotParam.centerPoint===''">
              <el-input v-model="plotParam.centerPoints" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="小区中心点" :label-width="formLabelWidth" v-if="plotParam.centerPoint!==''">
              <el-input v-model="plotParam.centerPoint" autocomplete="off"></el-input>
            </el-form-item>
            <!--            <el-form-item label="小区出入口" :label-width="formLabelWidth">-->
            <!--              <el-input v-model="plotParam.entrances" autocomplete="off"></el-input>-->
            <!--            </el-form-item>-->
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer" style="width: 800px;height: 100px">
          <el-button type="primary" @click="savePlot" style="margin-left: 40px">保存</el-button>
          <el-button @click="plotDetail">取 消</el-button>
        </div>
      </div>
      </span>
    </div>
    <div :style="typeMap">
      <div id="container" style="width: 1000px;height: 1000px;">
        <div class="search-bar" :style="typeSearch">
          <p>关键字搜索：<el-input v-model="input" @change="inputChange(input)" placeholder="请输入内容" id="tipinput" style="width:300px;padding-right: 10px;"></el-input></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {addPlot, deletePlot, plotList, updatePlot} from "@/api/system/smart/plot";
import AMapLoader from "@amap/amap-jsapi-loader";
import {getAreasCode, threeAreasList,getPlotById} from "@/api/system/smart/estate";
export default {
  name: 'App',
  data() {
    return {
      formInline:{
        pageNum: 1,
        pageSize: 10,
        plotName: '',
        areasId: '',
        userId: 0,
      },
      areasIds: [],
      areasList: {},
      typeMap: 'margin-left: -1000px;margin-top: -2000px',
      typeSearch: 'width: 500px;margin-top: -163px;margin-right: -25px;',
      dialogImageUrl: '',
      dialogVisible: false,
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogFormVisible1: true,
      searchInput: '',
      plots: [],// 用来存放 SmartRealPlot 列表数据,
      plotParam: {
        areasId: '',
        code: '',
        plotName: '',
        plotPic: '',
        address: '',
        outLine: '',
        centerPoint: '',
        entrances: '',
        centerPoints:'',
      },
      plotList: [],
      formLabelWidth: '120px',
      title: '',
      user: {},
      total: 0,

      // 地图
      dataForm: {
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      lnglat: [],
      markers: [[121.596134, 31.150678], [121.756955, 31.034795]],
      position: {},
      input: "",
      longitude: "",
      latitude: "",
      // 地图
      isAdvancedSearch: false
    };
  },
  created() {
    this.user = JSON.parse(sessionStorage.getItem('user'))
    this.fetchData();
    this.threeAreasList();
  },
  mounted() {
    this.initAMap();
  },
  methods: {
    /** 高级检索 */
    advancedSearch() {
      if (this.isAdvancedSearch == true){
        this.isAdvancedSearch = false
      }else if (this.isAdvancedSearch == false){
        this.isAdvancedSearch = true
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.formInline = {}
      this.formInline.pageNum = 1
      this.formInline.pageSize = 12
      this.fetchData();
    },
    /** 条件查询小区按钮 */
    onSubmit() {
      alert(JSON.stringify(this.formInline))
      this.fetchData();
    },
    aressChange() {
      this.plotParam.areasId = this.areasIds[this.areasIds.length - 1]
      this.formInline.areasId = this.areasIds[this.areasIds.length - 1]
      getAreasCode(this.plotParam.areasId).then(data => {
        this.plotParam.code = data.data.code
      })
    },
    threeAreasList() {
      threeAreasList().then(data => {
        this.areasList = data.data
      })
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "377ac4cca4c27c4c12b5938eb9e4a6f8",
      };
      AMapLoader.load({
        key: "7a4a86da37b07d754f299478047b8c10", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder", 'AMap.ToolBar',
          'AMap.Scale'],
        //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.AMap = AMap
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            // mapStyle: "amap://styles/darkblue",  // 地图样式，可以自定义
            resizeEnable: true,
            center: [121.441057, 31.316334], // 初始化地图中心点位置
          });

          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
          // 添加全屏按钮点击事件
          document.getElementById('fullscreenBtn').addEventListener('click', function () {
            if (this.map.getContainer().requestFullscreen) {
              this.map.getContainer().requestFullscreen();
            } else if (this.map.getContainer().mozRequestFullScreen) { /* Firefox */
              this.map.getContainer().mozRequestFullScreen();
            } else if (this.map.getContainer().webkitRequestFullscreen) { /* Chrome, Safari & Opera */
              this.map.getContainer().webkitRequestFullscreen();
            } else if (this.map.getContainer().msRequestFullscreen) { /* IE/Edge */
              this.map.getContainer().msRequestFullscreen();
            }
          }.bind(this)); // 使用bind确保this指向正确

        })
        .catch((e) => {
          console.log(e);
        });
    },
    inputChange(input) {
      this.plotParam.address = input
    },
    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.plotParam.centerPoints = [e.lnglat.getLng(), e.lnglat.getLat()]
      this.dataForm.kqLongitude = e.lnglat.getLng();
      this.dataForm.kqLatitude = e.lnglat.getLat();
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
        } else {
        }
      });
      this.dialogFormVisible = true
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };
      this.input = that.address; //把查询到的地址赋值到输入框
    },
    //  添加标记
    setMarker(lnglat) {
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
      console.log(this.markers)
    },
    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    //选中查询出的记录
    selectSite(e) {
      if (e.poi.location) {
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },

    // 地图结束

    fetchData() {
      this.formInline.userId = this.user.userId
      plotList(this.formInline).then(res => {
        this.plotList = res.data.rows;
        this.total = res.data.total;
      })
    },
    plotInsert() {
      this.title = '新增小区'
      this.dialogFormVisible = true;
      this.dialogFormVisible1 = false;
      this.typeMap = 'margin-left: -1000px;margin-top: -500px'
      this.typeSearch = 'width: 500px;margin-top: 63px;margin-right: -25px;'
    },
    plotDetail() {
      this.plotParam = {};
      this.areasIds = ''
      this.typeMap = 'margin-left: -1000px;margin-top: -2000px',
        this.typeSearch = 'width: 500px;margin-top: -163px;margin-right: -25px;',
        this.dialogFormVisible = false
      this.dialogFormVisible1 = true
    },
    savePlot() {
      // this.plotParam.address = this.input
      if (this.title === '新增小区') {
        const join = this.plotParam.centerPoints.join(',');
        this.plotParam.centerPoint = join
        addPlot(this.plotParam).then(res => {
          if (res.code === 200) {
            this.$message.success('新增成功')
          }
        })
        this.plotParam = {}
        this.fetchData()
      }``
      if (this.title === '修改小区') {
        updatePlot(this.plotParam).then(res => {
          if (res.code === 200) {
            this.$message.success('修改成功')
          }
        })
      }
      this.typeMap = 'margin-left: -1000px;margin-top: -2000px',
        this.typeSearch = 'width: 500px;margin-top: -163px;margin-right: -25px;',
        this.dialogFormVisible = false;
      this.dialogFormVisible1 = true;
      this.plotParam = {}
      this.fetchData()
    },
    /** 修改 */
    plotUpdate(id) {
      this.title = '修改小区'
      // this.plotParam = {...item}
      this.dialogFormVisible = true;
      this.dialogFormVisible1 = false;
      this.typeMap = 'margin-left: -1000px;margin-top: -500px'
      this.typeSearch = 'width: 500px;margin-top: 63px;margin-right: -25px;'
      getPlotById(id).then(res => {
        this.plotParam = res.data
      })
    },
    /** 详情 */
    plotDetails(id){
      this.$router.push({ path: '/community/disposition/details', query: { id: id } });
    },
    /** 删除 */
    plotDelete(id) {
      this.$confirm('此操作将永久删除该小区, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePlot(id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
          }
        })
        this.fetchData()
      }).catch(() => {
        this.$message({
          type: 'info',
        })
      })
    }
  },
  watch: {
    searchInput(newVal) {
      this.handleSearch();
    },
  },
};
</script>

<style scoped>

#app {
  display: flex;
  justify-content: left;
  align-items: center;
  margin-top: 20px;
}

.custom-button {
  border: none; /* 移除边框 */
  background-color: transparent; /* 移除背景色 */
  color: inherit; /* 继承父元素颜色 */
  padding: 0; /* 移除内边距 */
}

</style>
<style>
.second-div {
  display: block; /* 或者 display: inline-block; */
  width: 100%; /* 可以设置宽度或者其他样式 */
  margin-bottom: 10px; /* 可以添加间距 */
}

.box-card {
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .05);
  transition: all .3s;
  height: auto;
  overflow: hidden;
}

.search-bar {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 999; /* 设置一个较高的 z-index 值 */
  display: flex;
  justify-content: center;
  margin: 15px;
  background-color: rgba(255, 255, 255, 0.8); /* 透明的白色背景 */
  padding: 10px;
  border: 1px solid #ccc;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
